/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.api.controller;


import com.yami.shop.bean.app.param.PayParam;
import com.yami.shop.bean.enums.PayEntry;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.manager.impl.PayManager;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.PayInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @author LGH
 */
@RestController
@RequestMapping("/p/order")
@Api(tags = "订单支付接口")
@AllArgsConstructor
public class PayController {

    private final PayInfoService payInfoService;
    private final PayManager payManager;

    @PostMapping("/pay")
    @ApiOperation(value = "根据订单号进行支付", notes = "根据订单号进行支付")
    @SneakyThrows
    public ServerResponseEntity<?> pay(HttpServletResponse httpResponse, @Valid @RequestBody PayParam payParam) {
        YamiUser user = SecurityUtils.getUser();
        String userId = user.getUserId();
        if (!user.getEnabled()) {
            // 您已被禁用，不能购买，请联系平台客服
            throw new YamiShopBindException("yami.order.pay.user.disable");
        }
        PayInfoDto payInfo = payInfoService.pay(userId, payParam);
        payInfo.setBizUserId(user.getBizUserId());
        payInfo.setPayType(payParam.getPayType());
        payInfo.setApiNoticeUrl("/notice/pay/" + PayEntry.ORDER.value() + "/" + payParam.getPayType());
        payInfo.setReturnUrl(payParam.getReturnUrl());
        return payManager.doPay(httpResponse, payInfo);
    }

    @GetMapping("/isPay/{payEntry}/{orderNumbers}")
    @ApiOperation(value = "根据订单号查询该订单是否已经支付", notes = "根据订单号查询该订单是否已经支付")
    @ApiImplicitParam(name = "orderNumbers", value = "多个订单号拼接", required = true, dataType = "String")
    public ServerResponseEntity<Boolean> isPay(@PathVariable Integer payEntry, @PathVariable String orderNumbers) {
        YamiUser user = SecurityUtils.getUser();
        Integer count = payInfoService.queryPay(orderNumbers, user.getUserId(), payEntry);
        boolean res = count != null && count == 1;
        return ServerResponseEntity.success(res);
    }
}
